package com.kelin.mvvmlight.zhihu.retrofit;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dingzhihu on 15/5/7.
 */
public class RetrofitProvider {

    private static Retrofit retrofit;

    private RetrofitProvider() {
    }

//    public static Retrofit getInstance() {
//        if (retrofit == null) {
//            Gson gson = new GsonBuilder()
//                    .registerTypeAdapterFactory(new ApiTypeAdapterFactory("data"))
//                    .create();
//            retrofit = new Retrofit.Builder()
//                    .baseUrl("http://news-at.zhihu.com/")
//                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//                    .addConverterFactory(GsonConverterFactory.create(gson))
//                    .build();
//            if (BuildConfig.DEBUG) {
//                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
//                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//                client.interceptors().add(interceptor);
//            }
//
//        }
//        return retrofit;
//
//    }

    private final static int TIME_OUT = 60;//连接超时60s

    public static Retrofit getInstance() {
        if (retrofit == null) {
            Gson gson = new GsonBuilder()
                    .registerTypeAdapterFactory(new ApiTypeAdapterFactory("data"))
                    .create();
            okhttp3.OkHttpClient.Builder builder = new okhttp3.OkHttpClient.Builder();
            builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
            builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.interceptors().add(interceptor);
            //FaceBook 网络调试器，可在Chrome调试网络请求，查看SharePreferences,数据库等
            builder.interceptors().add(new StethoInterceptor());

            retrofit = new Retrofit.Builder()
                    .baseUrl("http://news-at.zhihu.com/")
                    .client(builder.build())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();

        }
        return retrofit;

    }
}
